package main

import (
	"fmt"
	"github.com/zhan3333/glog"
	"log"
	"log/syslog"
	"math/rand"
	"net"
	"os"
	"strconv"
	"time"
)

// 全局日志变量
var g_log *log.Logger

// 初始化全局变量
func initGlobal() {
	if len(os.Args) > 1 {
		if os.Args[1] == "-v" {
			fmt.Println(VER)
			os.Exit(0)
		}
	}

	g_log, _ = syslog.NewLogger(syslog.LOG_NOTICE, 0)
	//初始化随机种子
	rand.Seed(time.Now().UnixNano())
}

// 全局日志函数
func zLog(conn *net.Conn, args ...interface{}) {
	var sIP string

	if conn != nil {
		sIP = (*conn).RemoteAddr().String()
	} else {
		sIP = ""
	}
	sAtt := fmt.Sprint(args...)
	//g_log.Println(sIP, sAtt)
	glog.Channel("apid").Infof(sIP, sAtt)
}

// 整型时间转日期
func IntToTime(date int) time.Time {
	year := date / 10000
	month := (date % 10000) / 100
	day := date % 100
	if year < 2000 {
		year += 2000
	}
	sDate := fmt.Sprintf("%d-%02d-%02d", year, month, day)
	t, _ := time.Parse("2006-01-02", sDate)
	h, _ := time.ParseDuration("-1h")
	t = t.Add(8 * h)
	return t
}

// 时间转数字型日期和时间
func TimeToIntDateTime(tt time.Time) (d int, t int) {
	tempDate := tt.Format("060102")
	tempTime := tt.Format("150405")
	d, _ = strconv.Atoi(tempDate)
	t, _ = strconv.Atoi(tempTime)

	return
}

// 生成消息序号，WORD类型，小于65535的整数值
func CreateSerialNo() int {
	return rand.Intn(65535)
}

// 获取当前日期指定前后的日期
func today(dr int) int {
	t := time.Now().AddDate(0, 0, dr)
	y := t.Year()
	m := int(t.Month())
	d := t.Day()
	if y > 2000 {
		y = y - 2000
	}
	return y*10000 + m*100 + d
}

// 时间戳转整形
func TimeStampToInt(t int) int {
	tt := time.Unix(int64(t), 0)
	st := tt.Format("060102150405")
	it, _ := strconv.Atoi(st)

	return it
}

// 时间戳转整形时间和日期
func TimeStampToIntDateAndTime(t int) (int, int) {
	tt := time.Unix(int64(t), 0)
	st := tt.Format("060102150405")
	it, _ := strconv.Atoi(st)

	retD := int(it / 1000000)
	retT := int(it % 1000000)

	return retD, retT
}

// 时间戳转格式化日期
func TimeStampToString(t int, format string) string {
	if format == "" {
		format = "2006-01-02 15:04:05"
	}

	tt := time.Unix(int64(t), 0)
	return tt.Format(format)
}

// 转换车辆类型
func VehicleTypeToString(v string) string {
	switch v {
	case "1":
		return "小车"
	case "2":
		return "大车"
	case "3":
		return "挂车"
	case "4":
		return "车头"
	case "5":
		return "整车"
	case "6":
		return "第六车型"
	case "101":
		return "4x2"
	case "102":
		return "4x2(1)"
	case "103":
		return "6x2(D2-2)"
	case "104":
		return "6x2(D2)"
	case "105":
		return "6x2(D3)"
	case "201":
		return "矿 2X4"
	case "202":
		return "矿 2X8"
	}
	return ""
}
